package cn.hashq.netpostclient.session;

import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.AttributeKey;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

/**
 * 会话类
 * <p>
 * 将channel与客户端标识进行双向绑定
 * </p>
 *
 * @author HashQ
 * @since 1.0
 */
@Data
@Slf4j
public class ClientSession {

    public static final AttributeKey<ClientSession> SESSION_KEY = AttributeKey.valueOf("SESSION_KEY");

    /**
     * 通道
     */
    private Channel channel;

    private String key;


    public ClientSession(Channel channel, String key) {
        this.channel = channel;
        this.key = key;
    }

    public ClientSession reverseBind() {
        // 反向绑定
        channel.attr(ClientSession.SESSION_KEY).set(this);
        SessionMap.inst().addSession(this);
        return this;
    }

    public synchronized void writeAndFlush(Object pkg) {
        channel.writeAndFlush(pkg);
    }

    public static void closeSession(ChannelHandlerContext ctx) {
        ClientSession session = ctx.channel().attr(ClientSession.SESSION_KEY).get();
        session.close();
        SessionMap.inst().removeSession(session.getKey());
    }

    public synchronized void close() {
        ChannelFuture future = channel.close();
        future.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if (!future.isSuccess()) {
                    log.error("关闭通道异常");
                }
            }
        });
    }

}
